import { makeAutoObservable } from 'mobx';
import { isEmpty, isObject } from 'esy-ui';
import { createContext, useContext } from 'react';
import { ssSetJsonItem, ssGetJsonItem } from '@/utils/localStorage';

// 当前 class 类中的全局变量
export interface UserInfoStateType {
  Account: string;
  BirAddress: string;
  BirthDate: string;
  Cid: number;
  DynamicPwd: string;
  EmailCode: string;
  GameId: number;
  Gender: number;
  HeadImg: string;
  Id: number;
  IsFund: boolean;
  Level: number;
  LiveAddress: string;
  Name: string;
  NickName: string;
  SurName: string;
  Token: string;
  Mobile: string;
  Email: string;
}

export class UserInfoState {
  constructor() {
    makeAutoObservable(this);
    this.changeUserInfo = this.changeUserInfo.bind(this);
    this.clearUserInfo = this.clearUserInfo.bind(this);
    this.changeLocalMobx = this.changeLocalMobx.bind(this);
    this.updateBalance = this.updateBalance.bind(this);
    this.changeLocalMobx();
  }

  // 用户信息
  userInfo: UserInfoStateType | null = null;

  // 用户余额
  balance: number = 0.0;

  // 保存用户信息
  changeUserInfo(info?: UserInfoStateType) {
    if (isObject(info) && !isEmpty(info)) {
      if (this.userInfo) {
        this.userInfo = { ...this.userInfo, ...info };
        ssSetJsonItem('userInfo', { ...this.userInfo, ...info });
      } else {
        this.userInfo = { ...info };
        ssSetJsonItem('userInfo', { ...info });
      }
    }
  }

  // 更新用户余额
  updateBalance(score: number) {
    this.balance = score;
  }

  // 清除所有数据
  clearUserInfo() {
    ssSetJsonItem('userInfo', null);
    this.userInfo = null;
    this.balance = 0.0;
  }

  // 自动补充用户信息
  changeLocalMobx() {
    const userInfo = ssGetJsonItem('userInfo') || {};
    // 如果已经有值就保存起来
    if (userInfo?.Token) {
      this.changeUserInfo(userInfo);
    }
  }
}

// 利用createContext 创建storeContext
export const storeUserInfo = createContext(new UserInfoState());

// 导出一个hook 获取全局state的变量值
export const useUserInfoStore = () => useContext(storeUserInfo);
